<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { getToken } from '@/utils/cache/cookies'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { validatePhone } from '@/utils/formvalidate'
import { otherChargeRefund } from '@/api/expense'
import { otherChargeRefundRequestData } from '@/api/expense/types/expense'
import { queryTimeBikeHistoryLocus } from '@/api/bike'
import { UploadUserFile, UploadFile, UploadFiles } from 'element-plus'

const dialogVisible = ref<boolean>(false)
const open = () => {
  dialogVisible.value = true
}
defineExpose({ open })
/**
 * @param type - 退费类型
 * @param operateType - 操作类型
 */
const form = reactive<otherChargeRefundRequestData>({
  orderId: '',
  operateType: 1,
  type: 2,
  reason: '',
  applyAmount: 0,
  imageUrls: '',
  phone: '',
  bikeCode: ''
})
const formRef = ref<FormInstance | null>(null)

const rules = reactive<FormRules>({
  phone: [{ required: true, validator: validatePhone }],
  bikeCode: [{ required: true, message: '请选择车辆编号', trigger: 'blur' }],
  orderId: [{ required: true, message: '请选择行程编号', trigger: 'blur' }],
  type: [{ required: true, message: '请选择收费类型', trigger: 'change' }],
  applyAmount: [
    {
      required: true,
      message: '请输入金额',
      trigger: 'blur'
    },
    {
      type: 'pattern',
      message: '金额不能为负数',
      trigger: 'blur',
      pattern: /^(0|[1-9]\d*)(\.\d+)?$/
    }
  ],
  reason: [{ required: true, message: '请输入费用说明', trigger: 'blur' }],
  imageUrls: [{ required: true, message: '请上传相关图片', trigger: 'blur' }]
})
const orderIdloading = ref<boolean>(false)
const bikeCodeloading = ref<boolean>(false)
const formLoading = ref<boolean>(false)

const handlePhoneBlur = async () => {
  await getHisToryBikeCode()
}
const handleBikeCodeChange = async () => {
  await getHisToryOrderId()
}
const orderData = ref<string[]>([])
const bikeCodeData = ref<string[]>([])
const getHisToryOrderId = async () => {
  orderIdloading.value = true
  try {
    const res = await queryTimeBikeHistoryLocus({
      bikeCode: form.bikeCode,
      phone: form.phone,
      token: getToken() ?? '',
      pageNum: 1,
      pageSize: 10
    })
    if (res.statusCode === '0') {
      orderData.value = res.data.list.map((order) => order.orderId)
    }
    orderIdloading.value = false
  } catch (error) {
    console.error(error)
    orderIdloading.value = false
  }
}
const getHisToryBikeCode = async () => {
  bikeCodeloading.value = true
  try {
    const res = await queryTimeBikeHistoryLocus({
      bikeCode: form.bikeCode,
      phone: form.phone,
      token: getToken() ?? '',
      pageNum: 1,
      pageSize: 10
    })
    if (res.statusCode === '0') {
      bikeCodeData.value = [...new Set(res.data.list.map((order) => order.bikeCode))]
    }
    bikeCodeloading.value = false
  } catch (error) {
    console.error(error)
    bikeCodeloading.value = false
  }
}
const UploadHeader = reactive({
  Authorization: getToken() ?? ''
})
const href = ref<string>(import.meta.env.VITE_API + 'uploadOtherChargeImages')
const fileList = ref<UploadUserFile[]>([])
const handleFileSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  form.imageUrls = uploadFiles
    .map((file: UploadFile) => (file.response as ApiResponseData<string>).data)
    .join(',')
}
const handleRemove = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  form.imageUrls = uploadFiles
    .map((file: UploadFile) => (file.response as ApiResponseData<string>).data)
    .join(',')
}
const handleExeed = () => {
  ElMessage.warning('相关图片仅支持上传2张')
}
/** 取消后逻辑 */
const handleClose = () => {
  formRef.value?.resetFields()
  orderData.value = []
  bikeCodeData.value = []
  fileList.value = []
}
/** 取消 */
const cancle = () => {
  dialogVisible.value = false
}
const emits = defineEmits(['refresh'])
/** 提交 */
const submit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const res = await otherChargeRefund({
          orderId: form.orderId,
          applyAmount: form.applyAmount,
          type: form.type,
          operateType: 1,
          imageUrls: form.imageUrls,
          reason: form.reason,
          token: getToken() ?? ''
        })
        if (res.statusCode === '0') {
          ElMessage.success(res.data)
          emits('refresh')
          dialogVisible.value = false
        }
      } catch (error) {
        console.error(error)
      }
    }
  })
}
</script>

<template>
  <el-dialog v-model="dialogVisible" width="850" title="其他收费" @close="handleClose">
    <el-form :model="form" :rules="rules" label-width="120px" ref="formRef" v-loading="formLoading">
      <el-form-item label="用户手机号" prop="phone">
        <el-input v-model="form.phone" @blur="handlePhoneBlur" placeholder="请输入用户手机号" />
      </el-form-item>
      <el-form-item label="车辆编号" prop="bikeCode">
        <el-select
          v-model="form.bikeCode"
          @change="handleBikeCodeChange"
          remote
          :remote-method="getHisToryBikeCode"
          :loading="bikeCodeloading"
        >
          <el-option
            :label="bikeCodes"
            :value="bikeCodes"
            v-for="bikeCodes in bikeCodeData"
            :key="bikeCodes"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关联订单" prop="orderId">
        <el-select
          v-model="form.orderId"
          remote
          :remote-method="getHisToryOrderId"
          :loading="orderIdloading"
        >
          <el-option
            :label="orderIds"
            :value="orderIds"
            v-for="orderIds in orderData"
            :key="orderIds"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收费类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio label="车辆维修费" :value="2" />
          <el-radio label="违规费" :value="4" />
          <el-radio label="拖车费" :value="3" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="金额" prop="applyAmount">
        <el-input v-model="form.applyAmount" type="number">
          <template #prepend>￥</template>
        </el-input>
      </el-form-item>
      <el-form-item label="费用说明:" prop="reason">
        <el-input v-model="form.reason" type="textarea" :min="2" placeholder="请输入费用说明" />
      </el-form-item>
      <el-form-item label="相关图片" prop="imageUrls">
        <el-upload
          v-model:file-list="fileList"
          :limit="2"
          :headers="UploadHeader"
          :action="href"
          list-type="picture-card"
          :on-success="handleFileSuccess"
          :on-remove="handleRemove"
          :on-exceed="handleExeed"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancle" plain>取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </template>
  </el-dialog>
</template>

<style scoped></style>
